package logic

import (
	"context"

	"go-weixin/app/usercenter/rpc/internal/domain"
	"go-weixin/app/usercenter/rpc/internal/svc"
	"go-weixin/app/usercenter/rpc/pb/proto/usercenter"

	"github.com/zeromicro/go-zero/core/logx"
)

type TableLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	tableDomain *domain.TableDomain
}

func NewTableLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TableLogic {
	return &TableLogic{
		ctx:         ctx,
		svcCtx:      svcCtx,
		Logger:      logx.WithContext(ctx),
		tableDomain: domain.NewTableDomain(*svcCtx.ChenDb),
	}
}

func (l *TableLogic) TableAdd(in *usercenter.TableAddReq) (*usercenter.TableAddResp, error) {
	err := l.tableDomain.TableExistByUrl(in.Url)
	if err != nil {
		return nil, err
	}
	err = l.tableDomain.TableAdd(in.Name, in.Url, in.Method)
	if err != nil {
		return nil, err
	}
	return &usercenter.TableAddResp{}, nil
}

func (l *TableLogic) TableList(in *usercenter.TableListReq) (*usercenter.TableListResp, error) {
	tableList, err := l.tableDomain.TableList(in.Page)
	if err != nil {
		return nil, err
	}
	var resp []*usercenter.TableBase
	if len(tableList) > 0 {
		for _, table := range tableList {
			resp = append(resp, &usercenter.TableBase{
				Id:       table.Id,
				Name:     table.Name,
				Method:   table.Method,
				Url:      table.Url,
				CreateAt: table.CreateAt.Unix(),
				UpdateAt: table.UpdateAt.Unix(),
			})
		}
	}
	return &usercenter.TableListResp{
		TableList: resp,
	}, nil
}

func (l *TableLogic) TableUpdate(in *usercenter.TableUpdateReq) (*usercenter.TableUpdateResp, error) {
	err := l.tableDomain.TableUpdateExist(in.Id, in.Url)
	if err != nil {
		return nil, err
	}

	err = l.tableDomain.TableUpdate(in.Id, in.Name, in.Url, in.Method)
	if err != nil {
		return nil, err
	}
	return &usercenter.TableUpdateResp{}, nil
}
